package com.xxgc.helloworld.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxgc.helloworld.po.TokenInfo;
import com.xxgc.helloworld.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @program: helloworld
 * @description: JWT拦截器
 * @author: liutao
 * @create: 2022-03-07 15:55
 **/
public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TokenInfo info = new TokenInfo();
        // 获取请求头中令牌
        String token = request.getHeader("token");
        try {
            JWTUtils.verify(token);// 验证令牌
            return true;  // 放行请求
        } catch (SignatureVerificationException e) {
            info.setCode(-202);
            info.setMessage("无效签名");
        }catch (TokenExpiredException e){
            info.setCode(401);
            info.setMessage("登录过期");
        }catch (AlgorithmMismatchException e){
            info.setCode(-203);
            info.setMessage("算法不一致");
        }catch (Exception e){
            info.setCode(-204);
            info.setMessage("token无效");
        }
        // 将map以json的形式响应到前台  map --> json  (jackson)
        String json = new ObjectMapper().writeValueAsString(info);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}